package com.liull.netty.bytebuf;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;

import java.util.Arrays;

/**
 * @Author: liull
 * @Description: ByteBuf相关api学习
 * @Date: Created in 14:04 2021/1/30
 * @Modified By:
 */
public class ByteBufTest {

    public static void main(String[] args) {
        // 1.分配初始容量
        ByteBuf buffer = ByteBufAllocator.DEFAULT.buffer(6, 10);
        printByteBufInfo("allo buffer(6,10)", buffer);
        // 2.写入字节数组
        buffer.writeBytes(new byte[] {
                1, 2
        });
        printByteBufInfo("writeBytes", buffer);
        // 3.写入基本类型,int占四个字节
        buffer.writeInt(100);
        printByteBufInfo("writeInt(100)", buffer);
        // 2.写入字节数组
        // byte[] bs = "sss".getBytes();
        // System.out.println(Arrays.toString(bs));//得到 [115, 115, 115]
        // 4.达到初始容量之后在进行写入
        buffer.writeBytes(new byte[] {
                3, 4, 5
        });
        printByteBufInfo("write 3 Bytes", buffer);
        // 5.读取1
        byte[] dest = new byte[buffer.readableBytes()];
        buffer.readBytes(dest);
        printByteBufInfo("readBytes(" + buffer.readableBytes() + ")", buffer);
        printByteBufInfo("BeforeGetAndSet", buffer);
        System.out.println("getInt(2): " + buffer.getInt(2));
        buffer.setByte(1, 0);
        System.out.println("getByte(1): " + buffer.getByte(1));
        printByteBufInfo("AfterGetAndSet", buffer);
    }

    private static void printByteBufInfo(String step, ByteBuf buffer) {
        System.out.println("------" + step + "-----");
        System.out.println("readerIndex(): " + buffer.readerIndex());
        System.out.println("writerIndex(): " + buffer.writerIndex());
        System.out.println("isReadable(): " + buffer.isReadable());
        System.out.println("isWritable(): " + buffer.isWritable());
        System.out.println("readableBytes(): " + buffer.readableBytes());
        System.out.println("writableBytes(): " + buffer.writableBytes());
        System.out.println("maxWritableBytes(): " + buffer.maxWritableBytes());
        System.out.println("capacity(): " + buffer.capacity());
        System.out.println("maxCapacity(): " + buffer.maxCapacity());
    }
}
